package com.jujia.tmall.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.StackingBehavior;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.msf.application.MsfSdk;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jujia.tmall.adapter.MyFragmentPagerAdapter;
import com.jujia.tmall.base.BaseActivity;
import com.jujia.tmall.base.DoubleClickUtil;
import com.jujia.tmall.base.SealConst;
import com.jujia.tmall.cache.ServerAddress;
import com.jujia.tmall.cache.StringEluneCallback;
import com.jujia.tmall.entity.SiginVerifySource;
import com.jujia.tmall.fragment.OrderListFragment;
import com.jujia.tmall.util.ToolsKit;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpParams;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {
    private ArrayList<String> mTitleList = new ArrayList<>(2);
    private ArrayList<Fragment> mFragments = new ArrayList<>(2);
    public int frgChildIndex = 0;
    @Bind(R.id.tab_gank)
    TabLayout mtab;
    @Bind(R.id.vp_gank)
    ViewPager mPager;
    private SiginVerifySource mSiginVerifySource;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private OrderListFragment mOrderListFragment = OrderListFragment.newInstance(1);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = this;
        //初始化定位
        initLocation();
        initFragmentList();
        initView();

    }

    private void initView() {

        setMenuTitle(1, R.color.colorTheme, SealConst.APP_NAME, 0, 0);//back R.mipmap.titlebar_menu
        MyFragmentPagerAdapter myAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTitleList);
        mPager.setAdapter(myAdapter);
        // 左右预加载页面的个数
        mPager.setOffscreenPageLimit(2);
        myAdapter.notifyDataSetChanged();
        mtab.setTabMode(TabLayout.MODE_FIXED);
        mtab.setupWithViewPager(mPager);

        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                frgChildIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public void sign(String outerid, String orderIds) {
        String tpid = "3587405934";// 服务商标识
        Integer servicetype = 3;//服务类型固定为3
        MsfSdk.sign(tpid, outerid, orderIds, servicetype, this, 9999);
    }

    @Override
    public void onClick(View view) {
        if (DoubleClickUtil.check()) return;

        switch (view.getId()) {
            case R.id.login_btn:
                break;
        }
    }

    private void initFragmentList() {

        mTitleList.add("待处理");
//        mTitleList.add("10位核销码");
        mFragments.add(mOrderListFragment);
//        mFragments.add(SuperAwesomeCardFragment.newInstance(2));


    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }


    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        return mOption;
    }

    public void startLocation() {
        //根据控件的选择，重新设置定位参数
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }


    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    //定位完成的时间
//                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                //解析定位结果，
                String result = sb.toString();
                locationClient.stopLocation();
                new MaterialDialog.Builder(MainActivity.this)
                        .content(result + "")
                        .positiveText("确定")
                        .negativeText("取消")
                        .btnStackedGravity(GravityEnum.END)
                        .stackingBehavior(
                                StackingBehavior
                                        .ALWAYS) // this generally should not be forced, but is used for demo purposes
                        .show();

            } else {
                locationClient.stopLocation();
                new MaterialDialog.Builder(MainActivity.this)
                        .content("定位失败，loc is null")
                        .positiveText("确定")
                        .negativeText("取消")
                        .btnStackedGravity(GravityEnum.END)
                        .stackingBehavior(
                                StackingBehavior
                                        .ALWAYS) // this generally should not be forced, but is used for demo purposes
                        .show();
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 不退出程序，进入后台
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            return;
        }

        if (resultCode == RESULT_OK) {

            if (requestCode == 9999) {

                String msg = data.getStringExtra("ResultToPartner");

                if (msg != null && ToolsKit.isStringNotEmpty(msg)) {
                    mSiginVerifySource = JSONObject.parseObject(msg, SiginVerifySource.class);

                    if (mSiginVerifySource != null) {
                        if ("true".equals(mSiginVerifySource.getSiginsuccess()) && "true".equals(mSiginVerifySource.getVerifysuccess())) {
                            tellSystemSignResult(1, mSiginVerifySource.getOuterId());
                            toastActBtm("签到核销成功！");
                        }
                        if ("false".equals(mSiginVerifySource.getSiginsuccess()) && "true".equals(mSiginVerifySource.getVerifysuccess())) {
                            tellSystemSignResult(2, mSiginVerifySource.getOuterId());
                            toastActBtm("签到失败，核销成功！");
                        }
                        if ("true".equals(mSiginVerifySource.getSiginsuccess()) && "false".equals(mSiginVerifySource.getVerifysuccess())) {
                            tellSystemSignResult(3, mSiginVerifySource.getOuterId());
                            toastActBtm("签到成功，核销失败！");
                        }
                        if ("false".equals(mSiginVerifySource.getSiginsuccess()) && "false".equals(mSiginVerifySource.getVerifysuccess())) {
                            tellSystemSignResult(4, mSiginVerifySource.getOuterId());
                            toastActBtm("签到失败，核销失败！");
                        }
                    }


                }

            }

        }
    }

    private void tellSystemSignResult(final int sq, String orderId) {

        com.lzy.okgo.model.HttpHeaders headers = new com.lzy.okgo.model.HttpHeaders();
        HttpParams params = new HttpParams();
        params.put("action", "3");
        params.put("userid", orderId);//订单ID
        params.put("sq", sq);

        OkGo.post(ServerAddress.BEAN_UTILCONTROLLER_GETRESULTS).tag(mContext).headers(headers).params(params)
                .dialogIsShow(true)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringEluneCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                mOrderListFragment.dataRefresh();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                toastActBtm(e.getMessage() + "");
                mOrderListFragment.dataRefresh();
            }
        });

    }

}

